<?php

namespace App\Http\Controllers;

class IndexController
{

    /**
     * @function 与客户端server send event通信方式
     * @param    $callback    callable 回调，若返回数组代表要输出json，返回null代表本次循环不进行输出
     * @param    $millisecond int      数据分发间隔，单位：毫秒
     * @return   string
     * @other    void
     */
    public function sse($callback, $millisecond = 1000) {
        set_time_limit(0);
        ini_set('output_buffering', 'off');
        ini_set('zlib.output_compression', false);
        while (@ob_end_flush()) {

        }
        header('Content-Type: text/event-stream; Charset=UTF-8');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
        header('X-Accel-Buffering: no');
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Credentials: true");
        header('Access-Control-Allow-Methods: *');
        header('Access-Control-Allow-Headers: *');

        ob_start();
        while (true) {
            $callback_res = $callback();
            if($callback_res !== null) {
                $data = json_encode($callback_res, JSON_UNESCAPED_UNICODE);
                echo "data:{$data}\n\n";
            }
            ob_flush();
            flush();
            usleep($millisecond * 1000);
        }

    }


    public function send()
    {
        $this->sse(function() {
            return ['k' => 'v'];
        }, 1000);
    }

}
